<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 月光宝盒
-->
<template>
  <div>
    <van-form class="moon">
      <van-field
        v-model="ruleForm.username"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-checkbox-group v-model="result" direction="horizontal">
            <van-checkbox
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.name"
              checked-color="#e4393c"
              shape="square"
            >{{ option.label }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountList" :key="index" center :title="list.vestname">
        <template #right-icon>
          <van-switch
            v-model="list.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(list)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import dayjs from "dayjs";
import md5 from "js-md5";
import * as moon from "@/api/moon";
export default {
  name: "Moon",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        username: "17717751808",
        password: "Zz930329"
      },
      IntervalTime: 5,
      result: [2, 1],
      typeOptions: [
        {
          label: "垫付任务",
          name: 2
        },
        {
          label: "浏览任务",
          name: 1
        },
        {
          label: "礼品单任务",
          name: 3
        }
      ],
      startFlag: false,
      returnContent: [],
      show: false,
      accountList: [],
      uid: "",
      vestid: "",
      site: "",
      missionid: "",
      listid: "",
      timer: null,
      // 已接单标记
      isAcceptSuc: false,
activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 21 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 21 && this.index !== '') {
        this.activeIndex = this.index;
// 获取保存账号信息
        this.ruleForm.username = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || [2, 1];

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 21 && this.index !== '') {
      this.activeIndex = this.index;
// 获取保存账号信息
      this.ruleForm.username = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.type = this.item.type || [2, 1];
    }
  },
  methods: {
    // 开始接单
    onStart() {
      if (this.result.length === 0) {
        this.$toast("请选择任务类型");
        return false;
      }
      if (!this.startFlag) {
        // 登录
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        this.onLogin(this);
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 登录
    onLogin(_this) {
      clearInterval(_this.timer);
      let timestamp = dayjs().valueOf();
      moon.ajaxFun(
        moon.getLogin + timestamp,
        {
          type: "post",
          data: {
            username: _this.ruleForm.username,
            password: md5(_this.ruleForm.password),
            code: ""
          }
        },
        res => {
          if (res) {
            let message =
              res.message == "invaid username or password"
                ? "用户名或密码不正确!"
                : res.message == "failure"
                ? "无效的用户名或密码!"
                : "登录成功";
            _this.returnContent.unshift(alertMsg(message));
            if (res.code === 0) {
              _this.startFlag = false;
            } else {
              if (res.data[0].status == 4) {
                _this.returnContent.unshift(alertMsg("该号已被禁用"));
                _this.startFlag = false;
              } else {
                // 登录成功  => 保存账号信息
                saveInfo({
                  user: _this.ruleForm.username,
                  pass: _this.ruleForm.password,
                  type: _this.type,
                  index: _this.index
                });
                _this.uid = res.data[0].uid;
                _this.onGetdefaultbindvestlist(_this);
              }
            }
          } else {
            _this.returnContent.unshift(alertMsg("登录异常，重新登录中..."));
            _this.timer = setInterval(() => {
              _this.onLogin(_this);
            }, 2000);
          }
        }
      );
    },
    // 获取账号信息
    onGetdefaultbindvestlist(_this) {
      let timestamp = dayjs().valueOf();
      moon.ajaxFun(
        moon.getdefaultbindvestlist + timestamp,
        {
          type: "post",
          data: {
            uid: _this.uid
          }
        },
        res => {
          if (res.code === 1) {
            _this.accountList = res.data;
            if (_this.accountList.length === 1) {
              _this.onChange(_this.accountList[0]);
            } else {
              _this.show = true;
            }
          } else {
            _this.returnContent.unshift(alertMsg("请先绑定账号..."));
            _this.startFlag = false;
          }
        }
      );
    },
    // 选择账号
    onChange(list) {
      const _this = this;
      _this.returnContent.unshift(
        alertMsg("接单号：" + list.vestname + " 即将开始接单...")
      );
      _this.onGetApplyforamission(_this, list);
    },
    onGetApplyforamission(_this, list) {
      clearInterval(_this.timer);
      _this.vestid = list.vestid;
      let timestamp = dayjs().valueOf();
      moon.ajaxFun(
        moon.getApplyforamission + timestamp,
        {
          type: "post",
          data: {
            uid: _this.uid,
            vestid: _this.vestid + "," + 0 + "," + 0 + "," + 0 + "," + 0,
            missiontype: _this.result.join(",")
          }
        },
        res => {
          if (res.code === 1) {
            _this.onGetQueryapplyforamission(_this, list);
          } else {
            if (res.message == "have unfinished mission") {
              _this.returnContent.unshift(
                alertMsg("已有未完成订单，请先完成...")
              );
              _this.startFlag = false;
            } else {
              _this.returnContent.unshift(alertMsg(res.message));
              _this.timer = setInterval(() => {
                if (_this.startFlag) {
                  _this.onGetApplyforamission(_this, list);
                }
              }, _this.IntervalTime * 1000);
            }
          }
        }
      );
    },
    // 获取任务
    onGetQueryapplyforamission(_this, list) {
      _this.missionid = "";
      _this.listid = "";
      clearInterval(_this.timer);
      _this.returnContent.unshift(alertMsg("暂无任务，继续接单..."));
      let timestamp = dayjs().valueOf();
      moon.ajaxFun(
        moon.getQueryapplyforamission + timestamp,
        {
          type: "post",
          data: {
            uid: _this.uid
          }
        },
        res => {
          if (res.code === 1 && res.data[0].missioninfo != undefined) {
            alert(1);
            // 接单
            _this.missionid = res.data[0].missionid;
            _this.listid = res.data[0].listid;
            _this.site = res.data[0].site;
            _this.vestid = res.data[0].vestid;
            _this.onGetmembermissioninfo(_this);
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetApplyforamission(_this, list);
              }
            }, _this.IntervalTime * 1000);
          }
        }
      );
    },
    // 接单
    onGetmembermissioninfo(_this) {
      let timestamp = dayjs().valueOf();
      moon.ajaxFun(
        moon.getMembermissioninfo + timestamp,
        {
          type: "post",
          data: {
            site: _this.site,
            missionid: _this.missionid,
            listid: _this.listid,
            vestid: _this.vestid
          }
        },
        res => {
          if (res.code === 1) {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ['接单成功，请前往做单...']
          })
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetQueryapplyforamission(_this);
              }
            }, _this.IntervalTime * 1000);
          }
        }
      );
    }
  }
};
</script>
